package tasklist

import (
	"container/list"
)

type TaskList struct {
	List list.List
}

func NewTaskList() *TaskList {
	tasklist := new(TaskList)
	tasklist.List.Init()
	return tasklist
}
func (this *TaskList) InsertTask(task *Task) {
	task.Id = this.GetTaskCount() + 1
	this.List.PushBack(task)
}

func (this *TaskList) InsertTasks(tasks *[]*Task) {
	for _, task := range *tasks {
		this.InsertTask(task)
	}
}

func (this *TaskList) GetTaskCount() int {
	return this.List.Len()
}

func (this *TaskList) GetTaskById(taskid int) *Task {
	for e := this.List.Front(); e != nil; e = e.Next() {
		task := e.Value.(*Task)
		if taskid == task.Id {
			return task
		}
	}
	return nil
}

func (this *TaskList) FinishTask(taskid int) {
	task := this.GetTaskById(taskid)
	if task != nil {
		task.SetTaskFinish()
	}
}

type TaskFunc func(*Task)

func (this *TaskList) ForeachTaskDo(TaskFn TaskFunc) {
	for e := this.List.Front(); nil != e; e = e.Next() {
		TaskFn(e.Value.(*Task))
	}
}

func (this *TaskList) OutputArray() *[]*Task {
	tasks := make([]*Task, 0)
	for e := this.List.Front(); nil != e; e = e.Next() {
		task := e.Value.(*Task)
		if task != nil {
			tasks = append(tasks, task)
		}
	}
	return &tasks
}
